#include "FileParser.h"
#include <QDebug>
#include <stdio.h>
FileParser::FileParser()
{
}

//Parses the CSV file
FileParser::FileParser(char* fileName)
{
    qDebug() << "Inside FileParser Constructor";
    QFile file(fileName);
    file.open(QFile::ReadOnly);
    QTextStream stream(&file);
    //There is probably a better way for this O.o....Nested Templates wtf is this?!
    this->listItems = new QList<QStringList*>;
    this->headers = NULL;

	//read each line of the file
    while (!stream.atEnd())
    {
        QString line = stream.readLine();
        //First line is used as the header
        if (!this->headers)
        {
			//Cast the QList<QString>* into a QString List to use as headers
            this->headers = this->returnLineElements(line);
            continue;
        }

        this->listItems->append(this->returnLineElements(line));
    }

    file.close();
    qDebug() << "Exiting FileParser Constructor";
}

//Get a Qlist of headers for this object
QStringList* FileParser::getHeaders()
{
	return this->headers;
}

//Get a Qlist of headers for this object
QList<QStringList*>* FileParser::getListItems()
{
	return this->listItems;
}
//Parses a string a returns a Qlist of each CSV value in that string
QStringList* FileParser::returnLineElements(QString line)
{
    qDebug() << "in returnLineElements";
    QStringList* list = new QStringList();
    QString tempString = "";
    QTextStream lineStream(&line);
    QChar text;
    do
    {
        lineStream >> text;
        if (text == ',')
        {
            list->append(QString(tempString));
            tempString.clear();
        }
        else
        {
            tempString.append(text);
        }
    }
    while (!lineStream.atEnd());
    //Append last element into list
    list->append(QString(tempString));
    qDebug() << "exiting returnLineElements";
    return list;
}
